package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.commons.CollectionUtils;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.orm.mybatis.helper.PageHelper;
import com.pactera.jep.sys.code.DutySource;
import com.pactera.jep.sys.model.Position;
import com.pactera.jep.sys.model.Role;
import com.pactera.jep.sys.model.Staff;
import com.pactera.jep.sys.service.*;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.NameValuePair;
import com.pactera.jep.web.util.NVUtils;
import com.pactera.jep.web.util.RequestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="角色")
@RestController
@RequestMapping("/role")
public class RoleRestController extends BaseRestController<Role> {

	Logger logger = LoggerFactory.getLogger(RoleRestController.class);

	/**
	 * 结果中的记录总数
	 */
	private static final String RESULT_TOTAL = "total";

	/**
	 * 结果中的记录行数
	 */
	private static final String RESULT_ROWS = "rows";

	@Autowired
    RoleService roleService;

	@Autowired
    RoleStdService roleStdService;

	@Autowired
    RoleGroupMapService roleGroupMapService;

	@Autowired
    RoleGroupService roleGroupService;
	@Autowired
    DutyService dutyService;

	@Autowired
    PositionService positionService;

	@RequestMapping(value = "/select")
	public String select(String filters){
		List<Filter> filterList = new ArrayList<>();
		if(StringUtils.isNotBlank(filters)){
			filterList = JSONArray.parseArray(filters, Filter.class);
		}

		String rolesString = null;
		List<Role> roles =  roleService.select(filterList);
		if(CollectionUtils.isNotEmpty(roles)){
			rolesString = JSONArray.toJSON(roles).toString();
		}
		return rolesString;
	}

	@RequestMapping(value = "/selectRolesByStdcodeAndUnitCode")
	public String selectRolesByStdcodeAndUnitCode(String unitCodes, String roleStdCodes){
		String rolesString = null;
		List<Role> roles = roleService.selectRolesByStdcodeAndUnitCode(unitCodes, roleStdCodes);
		if(CollectionUtils.isNotEmpty(roles)){
			rolesString = JSONArray.toJSON(roles).toString();
		}
		return rolesString;
	}
	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(String token, Page<Role> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
		roleService.query(page, filters, orders);
	}

	/**
	 * 保存
	 * @param role
	 * @return
	 */
	@ApiOperation(value = "保存一条数据")
	@PostMapping(value = "/save")
	public Map<String, Object> save(@RequestBody Role role, String roleGroupCode) {

		Map<String, Object> tips = new HashMap<String, Object>();
		try
		{
			roleService.saveRole(role, roleGroupCode);

			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (Exception e)
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}

		return tips;
	}

	/**
	 * 删除
	 * @param code
	 * @return
	 */
	@ApiOperation(value = "根据编码删除一条数据")
	@PostMapping(value = "/remove/{code}")
	public Map<String, Object> remove(@PathVariable String code){

		Map<String, Object> tips = new HashMap<String, Object>();
		try
		{
			roleService.removeRole(code);
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
		}
		catch (Exception e)
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
		}

		return tips;
	}

	/**
	 * 验证提交的roleCode是否已经存在数据库中
	 * @param roleCode
	 * @return
	 */
	@ApiOperation(value = "验证提交的编码是否已经存在数据库中")
	@GetMapping(value = "/check")
	public Map<String, Object> check(String roleCode, HttpServletRequest request){

		Map<String, Object> tips = new HashMap<String, Object>();

		Role exist = roleService.get(roleCode);
		if(exist == null)
		{
			tips.put("valid", true);
		}
		else
		{
			tips.put("valid", false);
		}
		return tips;
	}


	/**
	 * 查询角色包含的用户
	 * @param page
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "查询角色包含的用户")
	@GetMapping(value = "/queryRoleStaff")
	public Map<String, Object> queryRoleStaff(Page<Staff> page, HttpServletRequest request){

		Map<String, Object> result = new HashMap<String, Object>();
		String roleCode = null;
		List<Filter> filters = RequestUtils.buildFilters(request);
		if(CollectionUtils.isNotEmpty(filters))
		{
			roleCode = (String) filters.get(0).getValue();
		}
		PageHelper.start(page);
		List<Staff> list = roleService.queryRoleStaff(roleCode);
		PageHelper.end(page, list);

		result.put(RESULT_TOTAL, page.getTotal());
		result.put(RESULT_ROWS, page.getResult());

		return result;
	}


	/**
	 * 以特殊格式获取某一层级的所有角色
	 * @return json格式返回
	 */
	@ApiOperation(value = "以特殊格式获取某一层级的所有角色")
	@GetMapping(value = "/queryAll")
	public List<NameValuePair> queryAll(String hierarchy){

		List<Filter> filters = new ArrayList<Filter>();
		if(StringUtils.isNotEmpty(hierarchy))
		{
			filters.add(new Filter("hierarchy", hierarchy));
		}
		List<Role> result = roleService.select(filters);

		return NVUtils.convert(result, result.size(), "roleCode", "roleName");
	}

	/**
	 * 根据角色组编码查询角色信息
	 * @param page
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "根据角色组编码查询角色信息")
	@GetMapping(value = "/queryByRoleGroupCode")
	public Map<String, Object> queryRole(Page<Role> page, HttpServletRequest request){

		Map<String, Object> result = new HashMap<String, Object>();
		String roleGroupCode = null;
		List<Filter> filters = RequestUtils.buildFilters(request);
		if(CollectionUtils.isNotEmpty(filters))
		{
			roleGroupCode = (String) filters.get(0).getValue();
		}
		PageHelper.start(page);
		List<Role> list = roleService.queryRoleByRoleGroup(roleGroupCode);
		PageHelper.end(page, list);

		result.put(RESULT_TOTAL, page.getTotal());
		result.put(RESULT_ROWS, page.getResult());

		return result;
	}
	/**
	 * 根据角色组编码查询角色信息
	 * @param
	 * @param
	 * @return
	 */
	@ApiOperation(value = "根据用户编码查询角色信息")
	@GetMapping(value = "/selectRoleByStaffCode/{staffCode}")
	public  List<Role> selectRoleByStaffCode(@PathVariable String staffCode){

		Map<String, Object> result = new HashMap<String, Object>();
		List<Role> list = dutyService.getStaffRoleList(staffCode, DutySource.ROLE.toString());
		return list;
	}


	/**
	 * 根据角色编码查询对应的岗位信息
	 * @param
	 * @param
	 * @return
	 */
	@ApiOperation(value = "根据角色编码查询对应的岗位信息")
	@PostMapping(value = "/selectPositions")
	public String selectPositions(String roles){
		List<String> rolsArrayList = CollectionUtils.split(roles);
		List<Filter> filters = new Filter.Builder().in("roleCode", rolsArrayList).build();
		List<Position> positions = positionService.select(filters);
		StringBuilder sb = new StringBuilder();
		for(Position position : positions){
			if(StringUtils.isNotBlank(sb.toString())){
				sb.append(",");
			}
			sb.append(position.getPositionCode());
		}
		return sb.toString();
	}

	/**
	 * 以特殊格式获取所有角色类型
	 * @return json格式返回
	 */
	@ApiOperation(value = "查询所有任务类型，并以 key-value 格式返回")
	@GetMapping(value = "/queryAllRole")
	public List<NameValuePair> queryAllRole(){
		List<Role> result = roleService.selectAll();
		return NVUtils.convert(result, result.size(), "roleCode", "roleName");
	}
}
